// pages/index/soundCard/soundCard.js
let m = 0,
  s = 0,
  timer = null,
  playTimer = null
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

//播放时长
var playTimeInterval
//录音时长
var recordTimeInterval
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: '', // 输出图片路径
    soundPath: '', // 输出录音路径
    isX: false, // 是否横向显示
    movableH: 0, // 相框高
    movableW: 0, // 相框宽
    imgWidth: 0, // 图片原始宽度
    imgHeight: 0, // 图片原始高度
    dragX: 0, // X轴拖动
    dragY: 0, // Y轴拖动
    scale: 1, // 缩放比例
    min: '00',
    sec: '00',

    playMin: '00',
    playSec: '00',

    isVioce: false, //是否有录音文件
    isStop: false, //停止
    isStart: true, //开始
    isPlay: false ,//播放

    //传递图片值至打印付款页面
    pictures:[]
  },
  onLoad: function(options) {
    let that = this,
      h,
      w
    wx.getImageInfo({ // 获取图片信息
      src: options.path,
      success: function(res) {
        w = res.width > res.height ? 680 : 550
        h = res.height / res.width * w
        that.setData({
          isX: res.width > res.height ? true : false,
          imgPath: options.path,
          movableH: h,
          movableW: w,
          imgWidth: res.width,
          imgHeight: res.height
        })
      }
    })
  },
  dragImg(e) { // 拖动
    console.log('1', e.detail)
    this.setData({
      dragX: e.detail.x,
      dragY: e.detail.y
    })
  },
  scaleImg(e) { // 缩放
    console.log('2', e.detail)
    this.setData({
      dragX: e.detail.x,
      dragY: e.detail.y,
      scale: e.detail.scale
    })
  },

  //全新的录音调用，老接口已经不维护了
  //开始录音
  start: function() {
    const options = {
      duration: 60000, //指定录音的时长，单位 ms，一分钟
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }

    let that = this
    clearInterval(timer)
    m = 0, s = 0, timer = null
    count()

    function count() {
      timer = setTimeout(() => {
        if (s == 60) {
          m = 1
          s = 0
          that.setData({
            min: s < 10 ? '0' + m : m,
            sec: s < 10 ? '0' + s : s
          })
          clearTimeout(timer)
        }
        s += 1
        that.setData({
          sec: s < 10 ? '0' + s : s
        })
        count()
      }, 1000)
    }
    //开始录音
    recorderManager.start(options);
    this.setData({
      isStart: false,
      isStop: true,
    })
    recorderManager.onStart(() => {
      console.log('录音开始')

    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },

  //暂停
  pause: function() {
    recorderManager.pause();
    recorderManager.onPause((res) => {
      console.log("暂停录音")
    })
  },

  //继续
  resume: function() {
    recorderManager.resume();
    recorderManager.onResume((res) => {
      console.log("继续录音")
    })
  },


  //停止，获取录音返回的临时文件地址
  stop: function() {
    clearTimeout(timer)
    recorderManager.stop();
    this.setData({
      isStop: false,
      isPlay: true
    })
    recorderManager.onStop((res) => {
      this.vioceFilePath = res.tempFilePath;
      console.log('停止录音', this.vioceFilePath)
      const {
        vioceFilePath
      } = res
    })
  },

  //播放声音
  play: function() {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.vioceFilePath;
    console.log(this.vioceFilePath)

    
    let that = this

    that.setData({
      isPlay:false
    })

    clearInterval(playTimer)
    m = 0, s = 0, playTimer = null
    count()

    function count() {
      playTimer = setTimeout(() => {
        if (s == 60) {
          m = 1
          s = 0
          that.setData({
            playMin: s < 10 ? '0' + m : m,
            playSec: s < 10 ? '0' + s : s
          })
          clearTimeout(playTimer)
        }
        s += 1
        that.setData({
          playSec: s < 10 ? '0' + s : s
        })
        count()
      }, 1000)
    }


    //播放监听
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })

    //自然播放结束
    innerAudioContext.onEnded((res) => {
      clearTimeout(playTimer)
    })

    //错误回调
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },


  cancel() { // 取消
    wx.navigateBack({})
  },
  outputSoundCard(e) { // 确定
    let that = this,
      h = this.data.movableH / 2,
      w = this.data.movableW / 2 //rpx -> px
    let ctx = wx.createCanvasContext('picBox') // 创建上下文
    ctx.drawImage(
      this.data.imgPath,
      this.data.dragX / w * this.data.imgWidth,
      this.data.dragY / h * this.data.imgHeight,
      this.data.imgWidth * this.data.scale,
      this.data.imgHeight * this.data.scale
    )
    ctx.draw() // 绘制
    console.log(this.data.imgPath)
    setTimeout(() => { // 绘制有延迟
      wx.canvasToTempFilePath({
        canvasId: 'picBox',
        destWidth: that.data.isX ? 1700 : 1100,
        destHeight: that.data.isX ? 1100 : 1700,
        quality: 1,
        success: function(res) {
          console.log(res.tempFilePath)
          that.data.pictures = [res.tempFilePath];
          wx.navigateTo({
            url: '../' + e.currentTarget.dataset.page + '/' + e.currentTarget.dataset.page + '?pictureNum=' + that.data.pictures.length + '&pictures=' + that.data.pictures
          })
        }
      })
    }, 500)
  }
})